﻿using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using mojoPortal.Web.RS.SBM.AppCode.Lib;

 
namespace mojoPortal.Web.RS.SBM.Telerik.Product.Add
{
    public partial class RSAddProduct : RSBasePage
    {
        private int _companyid = 0;
        private int _workorderid = 0;
        private int _Estimateid = 0;

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
        }

        
        protected void Page_Load(object sender, EventArgs e)
        {
            InitializeReadyServicePage("Add Parts To Estimate");

            RSUserIdentity userIdentity = GetRSUserIdentity();
            _companyid = userIdentity.RSCompanyId;
            if (!String.IsNullOrEmpty(Request.QueryString["workorderid"]))
                _workorderid = Convert.ToInt32(Request.QueryString["workorderid"].ToString());
            if (!String.IsNullOrEmpty(Request.QueryString["Estimateid"]))
                _Estimateid = Convert.ToInt32(Request.QueryString["Estimateid"].ToString());

            if (!IsPostBack)
            {
                BuildExpandedIndexes(_companyid);

                txtWorkOrderId.Text = _workorderid.ToString();

                if (Request.QueryString["isEstimate"] == "1")
                {
                    lblWorkOrderEstimateID.Text = "Estimate ID:";
                    
                }
            }
        }

        protected void btnSaveSelectedParts_Click(Object sender, EventArgs e)
        {
            List<SelectedItem> selParts = new List<SelectedItem>();
            if (Session["SelectedItems"] != null)
                selParts = (List<SelectedItem>)Session["SelectedItems"];

            int productid = 0;
            int quantity = 0;
            if (selParts.Count > 0)
            {
                //foreach (Part item in selParts)
                for (int i = 0; i < selParts.Count; i++)
                {
                    productid = Convert.ToInt32(selParts[i].ProductId);
                    quantity = Convert.ToInt32(selParts[i].Quantity);
                    if (_companyid > 0 && _workorderid > 0 && productid > 0 && quantity > 0)
                    {
                        SaveSelectedPartToWorkOrder(_companyid, _workorderid, productid, quantity);
                        Session["SelectedItems"] = null;
                    }
                }
            }

            string prevurl = string.Empty;
            if(Session["PreviousURL"] != null)
                prevurl = Session["PreviousURL"].ToString();
            else
                prevurl = Request.UrlReferrer.ToString();

            ucModalActionMessageControl.ShowModal("Parts Added Successfully!", prevurl, true);
        }
        protected void btnOK_Click(Object sender, EventArgs e)
        {
            if (Request.QueryString["isEstimate"] == "1")
                Response.Redirect("~/RS/SBM/RSEstimateDetail.aspx?&Estimateid=" + _Estimateid);
            else
                Response.Redirect("~/RS/SBM/RSWorkOrderDetail.aspx?&workorderid=" + _workorderid);
        }

        private void SaveSelectedPartToWorkOrder(int companyid, int WorkOrderid, int productid, int quantity)
        {
            SqlCommand sqlCmd = new SqlCommand();
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@ReturnValue", SqlDbType.Int, 0, ParameterDirection.ReturnValue, null);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@quantity", SqlDbType.Int, 0, ParameterDirection.Input, quantity);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@productid", SqlDbType.Int, 0, ParameterDirection.Input, productid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@WorkOrderid", SqlDbType.Int, 0, ParameterDirection.Input, WorkOrderid);
            SQLHelper.AddParamToSQLCmd(sqlCmd, "@companyid", SqlDbType.Int, 0, ParameterDirection.Input, companyid);

            SQLHelper.SetCommandType(sqlCmd, CommandType.Text, "INSERT INTO rs_tblWorkOrderPart (WorkOrderid, productid, quantity, companyid, unitprice) VALUES(@WorkOrderid, @productid, @quantity, @companyid, (select i.unitprice from rs_tblInventory i where i.productid=@productid and i.companyid=@companyid))");
            SQLHelper.ExecuteScalarCmd(sqlCmd);

            int returnValue = Convert.ToInt32(sqlCmd.Parameters["@ReturnValue"].Value);
      
        }

        private void BuildExpandedIndexes(int companyid)
        {
            String strSQL = "select * from rs_tblinventory where (ParentId is null or ParentId=0) and companyid=@companyid";
            SqlCommand myCommand;
            SqlParameter param;
            SqlConnection myConnection;
            myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[GetRSCompanyConnectionString()].ToString());
            myCommand = new SqlCommand(strSQL, myConnection);
            SqlDataReader myDataReader;

            param = new SqlParameter();
            param.SqlDbType = SqlDbType.Int;
            param.ParameterName = "@companyid";
            param.Value = companyid;
            myCommand.Parameters.Add(param);

            myConnection.Open();
            myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
            if (myDataReader.HasRows)
            {
                int i = 0;
                while (myDataReader.Read())
                {
                    //fulladdress = myDataReader["LocationName"].ToString() + " - ";
                    RadTreeList1.ExpandedIndexes.Add(new TreeListHierarchyIndex { LevelIndex = i, NestedLevel = 0 });
                    i = i + 1;
                }
            }
            myConnection.Close();
        }
        
        protected void RadTreeList1_NeedDataSource(object sender, TreeListNeedDataSourceEventArgs e)
        {
            RadTreeList1.DataSource = InventoryData.GetData(_companyid);
        }

        protected void gvSelectedPartList_RowDeleting(Object sender, GridViewDeleteEventArgs e)
        {
            string selectedid = Convert.ToString(gvSelectedPartList.DataKeys[e.RowIndex].Value);
            RemoveSelectedItemFromList(selectedid);
        }
        protected void RadTreeList1_ItemCommand(object sender, TreeListCommandEventArgs e)
        {
            if (e.CommandName == RadTreeList.SelectCommandName)
            {
                //item is being selected    
                if (e.Item is TreeListDataItem)
                {
                    TreeListDataItem item = e.Item as TreeListDataItem;
                    DeselectAllExceptID(item["ProductID"].Text);
                    if (item.FindControl("txtItemQuantity") != null)
                    {
                        TextBox txtQty = item.FindControl("txtItemQuantity") as TextBox;
                        txtQty.BackColor = System.Drawing.Color.White;
                        txtQty.ReadOnly = false;
                    }
                    if (item.FindControl("btnAddItem") != null)
                    {
                        Button btnAdd = item.FindControl("btnAddItem") as Button;
                        btnAdd.Visible = true;
                    }
                }
            }
            if (e.CommandName == RadTreeList.DeselectCommandName)
            {
                if (e.Item is TreeListDataItem)
                {
                    TreeListDataItem item = e.Item as TreeListDataItem;
                    string deselectedID = item["ProductID"].Text.Trim();

                    if (item.FindControl("txtItemQuantity") != null)
                    {
                        TextBox txtQty = item.FindControl("txtItemQuantity") as TextBox;
                        txtQty.Text = "";
                        txtQty.BackColor = System.Drawing.Color.LightGray;
                        txtQty.ReadOnly = true;
                    }
                    if (item.FindControl("btnAddItem") != null)
                    {
                        Button btnAdd = item.FindControl("btnAddItem") as Button;
                        btnAdd.Visible = false;
                    }
                }
            }
            if (e.CommandName == RadTreeList.ExpandCollapseCommandName)
            {
                DeselectAllExceptID("");
            }
            if (e.CommandName == "Add")
            {
                if (e.Item is TreeListDataItem)
                {
                    TreeListDataItem item = e.Item as TreeListDataItem;
                    string selectedID = item["ProductID"].Text.Trim();
                    string selectedProdName = "";
                    if (item.FindControl("hlProductLink") != null)
                    {
                        HyperLink hlProdName = item.FindControl("hlProductLink") as HyperLink;
                        selectedProdName = hlProdName.Text.Trim();
                    }
                    string selectedQty = "";
                    if (item.FindControl("txtItemQuantity") != null)
                    {
                        TextBox txtQty = item.FindControl("txtItemQuantity") as TextBox;
                        selectedQty = txtQty.Text.Trim();
                    }
                    AddSelectedItemToList(selectedID, selectedProdName, selectedQty);
                }
            }

        }

        private void RemoveSelectedItemFromList(string selectedid)
        {
            List<SelectedItem> selParts = new List<SelectedItem>();
            if (Session["SelectedItems"] != null)
                selParts = (List<SelectedItem>)Session["SelectedItems"];

            if (selParts.Count > 0)
            {
                for (int i = 0; i < selParts.Count; i++)
                {
                    if (selParts[i].ProductId == selectedid)
                    {
                        selParts.RemoveAt(i);
                        i = selParts.Count + 1;
                    }
                }
            }

            Session["SelectedItems"] = selParts;
            gvSelectedPartList.DataSource = selParts;
            gvSelectedPartList.DataBind();

            if (gvSelectedPartList.Rows.Count > 0)
                btnSaveSelectedParts.Visible = true;
            else
                btnSaveSelectedParts.Visible = false;
        }
        private void AddSelectedItemToList(string prodid, string prodname, string prodqty)
        {

            List<SelectedItem> selParts = new List<SelectedItem>();
            if (Session["SelectedItems"] != null)
                selParts = (List<SelectedItem>)Session["SelectedItems"];

            bool bFound = false;
            if (selParts.Count > 0)
            {
                //foreach (Part item in selParts)
                for (int i = 0; i < selParts.Count; i++)
                {
                    if (selParts[i].ProductId == prodid)
                    {
                        selParts[i].ProductName = prodname;
                        selParts[i].Quantity = prodqty;
                        bFound = true;
                        i = selParts.Count;
                    }
                }
            }
            if (!bFound)
                selParts.Add(new SelectedItem(prodid, prodname, prodqty));

            Session["SelectedItems"] = selParts;
            gvSelectedPartList.DataSource = selParts;
            gvSelectedPartList.DataBind();

            if (gvSelectedPartList.Rows.Count > 0)
                btnSaveSelectedParts.Visible = true;
            else
                btnSaveSelectedParts.Visible = false;
        }

        private void DeselectAllExceptID(string exceptID)
        {
            foreach (TreeListDataItem item in RadTreeList1.Items)
            {
                if (exceptID != item["ProductID"].Text)
                {
                    item.Selected = false;
                    if (item.FindControl("txtItemQuantity") != null)
                    {
                        TextBox txtQty = item.FindControl("txtItemQuantity") as TextBox;
                        txtQty.Text = "";
                        txtQty.BackColor = System.Drawing.Color.LightGray;
                        txtQty.ReadOnly = true;
                    }
                    if (item.FindControl("btnAddItem") != null)
                    {
                        Button btnAdd = item.FindControl("btnAddItem") as Button;
                        btnAdd.Visible = false;
                    }
                }
            }
        }

        protected void RadTreeList1_ItemDataBound(object sender, TreeListItemDataBoundEventArgs e)
        {
            if (e.Item is TreeListDataItem)
            {
                TreeListDataItem dataItem = e.Item as TreeListDataItem;
                HyperLink editLink = (HyperLink)e.Item.FindControl("hlProductLink");
                editLink.Attributes["href"] = "../../RSManageProduct.aspx?productid=" + dataItem["ProductID"].Text.Trim();
            }
        }
    }
    public class InventoryData
    {
        public static List<Part> GetData(int companyid)
        {
            List<Part> list = new List<Part>();

            string productid;
            string productname;
            string quantity;
            decimal? price;
            bool instock;
            string parentid;

            if (companyid > 0)
            {
                String strSQL = "SELECT Productid, ProductName, UnitsInStock, UnitPrice, ParentID FROM rs_tblInventory WHERE CompanyId=@CompanyId AND Discontinued=0 ORDER BY ParentId, ProductId";
                SqlCommand myCommand;
                SqlParameter param;
                SqlConnection myConnection;
                myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings[RSSBMCommonFunctions.GetRSCompanyConnectionString()].ToString());
                myCommand = new SqlCommand(strSQL, myConnection);
                SqlDataReader myDataReader;

                param = new SqlParameter();
                param.SqlDbType = SqlDbType.Int;
                param.ParameterName = "@Companyid";
                param.Value = companyid;
                myCommand.Parameters.Add(param);

                myConnection.Open();
                myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
                if (myDataReader.HasRows)
                {
                    while (myDataReader.Read())
                    {
                        productid = myDataReader["productid"].ToString();
                        productname = myDataReader["productname"].ToString();
                        price = Convert.ToDecimal(myDataReader["unitprice"].ToString());
                        quantity = myDataReader["unitsinstock"].ToString();
                        parentid = myDataReader["parentid"].ToString();
                        instock = false;
                        if (quantity.Length > 0)
                        {
                            if (Convert.ToInt16(quantity) > 0)
                                instock = true;
                        }

                        list.Add(new Part(productid, productname, quantity, price, instock, parentid));
                    }

                }

                myConnection.Close();

            }
            return list;
        }
    }
    
    public class Part
    {
        public string ProductID { get; set; }
        public string ProductName { get; set; }
        public string Quantity { get; set; }
        public decimal? Price { get; set; }
        public bool InStock { get; set; }
        public string ParentID { get; set; }

        public Part(string productid, string productname, string quantity, decimal? price, bool instock, string parentid)
        {
            ProductID = productid;
            ProductName = productname;
            Quantity = quantity;
            Price = price;
            InStock = instock;
            ParentID = parentid;
        }
    }

    public class SelectedItem
    {
        public string ProductId { get; set; }
        public string ProductName { get; set; }
        public string Quantity { get; set; }

        public SelectedItem(string pid, string pname, string pqty)
        {
            ProductId = pid;
            ProductName = pname;
            Quantity = pqty;
        }
    }
}